package com.citycloud.ccuap.tc.oauth2;

import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.citycloud.ccuap.framework.util.ClassUtil;
import com.citycloud.ccuap.tc.oauth2.config.CustomerProperties;
import com.citycloud.ccuap.tc.oauth2.dto.ProjectDto;
import com.citycloud.ccuap.tc.oauth2.mapper.ProjectMapper;

@Component
@Order(1)
public class Oauth2CmdLine implements CommandLineRunner {
	@Value("${tc.authenticationFrontendUrl}")
	private String authenticationFrontendUrl;

	@Value("${tc.authenticationBackendUrl}")
	private String authenticationBackendUrl;

	@Value("${tc.authorizationProjectId}")
	private Long authorizationProjectId;

	@Resource
	private ProjectMapper projectMapper;

	private static Logger logger = LoggerFactory.getLogger(Oauth2CmdLine.class);

	@Override
	public void run(String... arg0) {
		logger.info("开始获取自定义参数配置...");
		try {
			CustomerProperties.authenticationFrontendUrl = authenticationFrontendUrl;
			CustomerProperties.authenticationBackendUrl = authenticationBackendUrl;
			CustomerProperties.authorizationProjectId = authorizationProjectId;

			Map<String, Object> projectMap = projectMapper.selectProjectByProjectId(authorizationProjectId);
			if (projectMap == null) {
				logger.error("通过tc.authorizationProjectId:" + authorizationProjectId + " 获取平台管控站点信息失败！！");
			} else {
				ProjectDto project = new ProjectDto();
				ClassUtil.convertMap2Entity(projectMap, project, true, "");

				CustomerProperties.authorizationUrl = project.getUrl();
				CustomerProperties.authorizationClientId = project.getClientId();
			}
		} catch (Exception e) {
			logger.error("配置自定义参数时发生异常！", e);
		} finally {
			logger.info("自定义参数配置结束");
		}
	}
}
